﻿using System;
using System.Collections.Generic;
using System.Security.Policy;

namespace Peak.Web.Controllers.Services
{
  public class BackLink : IBackLink
  {
    List<Uri> _returnUrls = new List<Uri>();
    public Uri CurrentUrl{ get; set;}
  
    public void Push(Uri link)
    {
      Uri l = _returnUrls.Find(f => f.AbsolutePath == link.AbsolutePath);
      if(l != null)
      {
        int index = _returnUrls.IndexOf(l);
        _returnUrls.RemoveRange(index,_returnUrls.Count - index);        
      }
      else if (CurrentUrl != null && CurrentUrl.AbsolutePath != link.AbsolutePath)
      {
        _returnUrls.Add(CurrentUrl);      
      }
      CurrentUrl = link;
    }

    public Uri Pop()
    {      
      if(_returnUrls.Count == 0)
        return null;

      CurrentUrl = _returnUrls[_returnUrls.Count - 1];
      _returnUrls.Remove(CurrentUrl);
      return CurrentUrl;
    }

    public void Reset()
    {
      CurrentUrl = null;
      _returnUrls.Clear();
    }

    public int Count
    {
      get
      {
        return _returnUrls.Count;
      }
    }

    public override string ToString()
    {      
      string result = "";
      if (CurrentUrl != null)
        result = CurrentUrl.AbsolutePath + "<br/><br/>";    

      foreach(Uri link in _returnUrls)
      {
        result += link.AbsolutePath + "<br/>";
      }
      return result;
    }
  }
}
